/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.core;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.motoo.filter.DefaultFilterChainBuilder;
import com.google.code.motoo.filter.DefaultIoFilterChainBuilder;
import com.google.code.motoo.filter.IoFilterChain;
import com.google.code.motoo.utils.IoSessionUtils;

/**
 * 类说明:负责channel注册的类，创建新的IoSession，同时初始化FilterChain
 * 
 * @author  linfengqi
 * @version 1.0, 2009-2-25
 */
public class Acceptor {
	
	private ServerSocketChannel acceptChannel;
	private Selector acceptSelector = null; 
	private volatile boolean running = true;
	private int backlog = 50;
    private boolean reuseAddress = false;
    private boolean keepAlive = true;
	private IoHandler ioHandler;
	private CopyOnWriteArrayList<IoSessionListener> sessionListeners;
	private Reader reader = new Reader();
	private WriteExecutor writeExecutor = new WriteExecutor();
	private TaskExecutor taskExecutor = new TaskExecutor();
	private DefaultIoFilterChainBuilder ioFilterChain = new DefaultIoFilterChainBuilder();
	private DefaultFilterChainBuilder filterChain = new DefaultFilterChainBuilder();
	public final static Log log = LogFactory.getLog(Acceptor.class);
	
	public Acceptor() {
	}
	
	public void destory() {
		running = false;
	}
	
	public void bind(InetSocketAddress address) throws IOException {
		if (ioHandler == null) throw new RuntimeException("IoHandler is null!");
		bind0(address);
		log.info("server is startup on " + address.getPort());
		startup();
	}
	
	public void bind0(InetSocketAddress address) throws IOException {
		acceptChannel = ServerSocketChannel.open();
		acceptChannel.configureBlocking(false);
        ServerSocket socket = acceptChannel.socket();
        socket.setReuseAddress(isReuseAddress());
        socket.bind(address, getBacklog());
		acceptSelector = Selector.open();
		acceptChannel.register(acceptSelector, SelectionKey.OP_ACCEPT);
	}
	
	public void startup() {
		while (running) {
			SelectionKey key = null;
			try {
				acceptSelector.select();
				Iterator<SelectionKey> iter = acceptSelector.selectedKeys().iterator();
				while (iter.hasNext()) {
					key = iter.next();
					iter.remove();
					if (key.isValid()) {
						if (key.isAcceptable())
							doAccept(key);
					}
					
					key = null;
				}
			} catch (IOException e) {
				log.fatal("listen selector happens error!" + e);
			}
		}
	}
	
	// 接收请求
	private void doAccept(SelectionKey key){
		ServerSocketChannel server = (ServerSocketChannel) key.channel();
		SocketChannel channel = null;
		IoSession session = null;
		try {
			//设置非阻塞模式
			server.configureBlocking(false);
			channel = server.accept();
			session = new DefaultIoSession(channel, ioHandler);
			addAttributes(session);
			reader.registerChannel(channel, session);
			IoSessionUtils.addIoSession(channel, session);
			
			for (IoSessionListener listener : sessionListeners) {
				listener.created(session);
            }
			
			ioHandler.sessionCreated(session);
		} catch (Exception e) {
			try {
				if (session != null)
					ioHandler.exceptionCaught(session, e);
			} catch (Exception e1) {
				log.warn("register channel happen error!", e1);
			}
		}
	}
	
	private void addAttributes(IoSession session) throws Exception {
		IoFilterChain chain = (IoFilterChain) session.getAttribute(IoSession.IO_FILTER_CHAIN);
		ioFilterChain.buildFilterChain(chain);
		filterChain.buildFilterChain(session.getFilterChain());
		session.setAttribute(IoSession.TASK_EXECUTOR, taskExecutor);
		session.setAttribute(IoSession.WRITE_EXECUTOR, writeExecutor);
		session.setAttribute(IoSession.KEEP_ALIVE, keepAlive);
	}

	public Selector getAcceptSelector() {
		return acceptSelector;
	}

	public DefaultIoFilterChainBuilder getIoFilterChain() {
		return ioFilterChain;
	}

	public DefaultFilterChainBuilder getFilterChain() {
		return filterChain;
	}

	public void setIoHandler(IoHandler ioHandler) {
		this.ioHandler = ioHandler;
	}

	public Reader getReader() {
		return reader;
	}

	public WriteExecutor getWriteExecutor() {
		return writeExecutor;
	}

	public TaskExecutor getTaskExecutor() {
		return taskExecutor;
	}

	public int getBacklog() {
		return backlog;
	}

	public void setBacklog(int backlog) {
		this.backlog = backlog;
	}

	public boolean isReuseAddress() {
		return reuseAddress;
	}

	public void setReuseAddress(boolean reuseAddress) {
		this.reuseAddress = reuseAddress;
	}

	public void setKeepAlive(boolean keepAlive) {
		this.keepAlive = keepAlive;
	}
	
}
